<? namespace pft;
use LaneWeChat\Core\Db;

/**
 *会员类.
 *调用成员函数获取登录会员相关信息
 */
class Member{
    /**
     *会员ID
     *@var int
     */
    public $memberID;
    
    /**
     *所属分销商ID,非普通会员与会员ID一致
     *@var int
     */
    public $fid;
    
    /**
     *会员信息
     *@var array
     */
    public $m_info;
    
    /**
     *票付通内部接口对象
     *@var object
     */
    public $s;
    
    /**
     *构造函数.
     *@param $s 票付通内部接口对象
     *@int $memberID 会员ID
     */
    public function __construct($s,$memberID){
        $this->fid=$this->memberID=$memberID;
        $str="select * from pft_member where id=".$memberID." limit 1";
        $GLOBALS['le']->query($str);
        $this->m_info=$GLOBALS['le']->fetch_assoc();
        $this->s=$s;
    }
    
    /**
     *会员信息函数.
     *@return array 返回会员信息键值数组
     */
    public function info(){
        return $this->m_info;
    }
    
    /**
     *查询常用联系人函数.
     *@param int $sort 按键值顺序|逆序排列
     *@return array 常用联系人键值数组，键联系人姓名，值联系人手机
     */
    public function cinfos($sort=1){
        $str="select cinfos from pft_member_extinfo where fid=".$this->memberID;
        $GLOBALS['le']->query($str);
        $GLOBALS['le']->fetch_assoc();
        $cinfos=$GLOBALS['le']->f("cinfos");
        $out=array();
        if($cinfos){
            $cinfos=explode("|",$cinfos);
            if($sort==-1)
                krsort($cinfos);
            foreach($cinfos as $row){
                $info=explode(":",$row);
                $out[$info[0]]=$info[1];
            }
        }
        return $out;
    }
    
    /**
     *添加常用联系人函数.
     *@param string $ordername 联系人姓名
     *@param string $ordertel 联系人手机
     */
    public function addCinfo($ordername,$ordertel){
        
        if(!$ordername) return false;
        define("MAXNUM",9); //最多联系人数目
        $cinfos=$this->cinfos();
        $cname=array();
        $ctel=array();
        foreach($cinfos as $k=>$v){
            if($k){
                $cname[]=$k;
                $ctel[]=$v;
            }
        }
        $key=array_search($ordername,$cname);
        if($key===false){
            if(count($cname)>=MAXNUM){//如果数目大于做大允许数
                array_shift($cname);
                array_shift($ctel);
            }
            array_push($cname,$ordername);
            array_push($ctel,$ordertel);
        }else{
            $ctel[$key]=$ordertel;
            if($key!=(count($cname)-1)){//该联系人存在，位置移后
                $t=$cname[$key+1];
                $cname[$key+1]=$cname[$key];
                $cname[$key]=$t;
                $t=$ctel[$key+1];
                $ctel[$key+1]=$ctel[$key];
                $ctel[$key]=$t;
            }
        }
                        
        $cinfos=array_combine($cname,$ctel);
        $out=array();
        
        foreach($cinfos as $k=>$v){
            $out[]=$k.":".$v;
        }
        $out=implode("|",$out);
        $str="update pft_member_extinfo set cinfos='$out' where  fid=".$this->memberID;
        $GLOBALS['le']->query($str);
    }
    
    /**
     *查询会员账户余额函数.
     *@return int 余额分单位
     */
    public function money(){
        $fundXml=$this->s->PFT_Member_Fund($this->memberID);
        $fundXml=simplexml_load_string($fundXml);
        return (string)$fundXml->Rec->UUamoney;
    }
    
        
    /**
     *查询会员账户可用授信额度函数.
     *返回值是最大可欠额度加上已有额度
     *@return int 额度分单位
     */
    public function tmoney($aid){
        $fundXml=$this->s->PFT_Member_Fund($this->memberID,2,$aid);
        $fundXml=simplexml_load_string($fundXml);
        $basefund=$fundXml->Rec->UUbasecredit;
        $fundXml=$this->s->PFT_Member_Fund($this->memberID,1,$aid);
        $fundXml=simplexml_load_string($fundXml);
        $kfund=$fundXml->Rec->UUkmoney;
        $usefund=$basefund+$kfund;//可用购买额度
        return $usefund;
    }
    
    /**
     *查询会员账户供应产品数函数.
     *@return int
     */
    public function pronum(){
        $str="select count(*) as num from uu_products where  p_status in (0,2,3,4,5) and apply_did=".$this->memberID;
        $GLOBALS['le']->query($str);
        $GLOBALS['le']->fetch_assoc();
        return $GLOBALS['le']->f("num");
    }
    
    /**
     *查询会员供应产品上架数函数.
     *@return int
     */
    public function upProNum(){
        $str="select count(*) as num from uu_products where apply_limit=1 and p_status in (0,2,3,4,5) and apply_did=".$this->memberID;
        $GLOBALS['le']->query($str);
        $GLOBALS['le']->fetch_assoc();
        return $GLOBALS['le']->f("num");
    }
    
    /**
     *查询会员供应产品下架数函数.
     *@return int
     */
    public function downProNum(){
        $str="select count(*) as num from uu_products where apply_limit=2 and p_status in (0,2,3,4,5) and apply_did=".$this->memberID;
        $GLOBALS['le']->query($str);
        $GLOBALS['le']->fetch_assoc();
        return $GLOBALS['le']->f("num");
    }
    public function distributorNum(){
        $str="select count(*) as num from pft_member_relationship r join pft_member m on r.son_id=m.id where r.status=0 and m.status=0 and r.ship_type=0 and parent_id=".$this->memberID;
        $GLOBALS['le']->query($str);
        $GLOBALS['le']->fetch_assoc();
        return $GLOBALS['le']->f("num");
    }
    
    /**
     *查询会员合作分销商函数.
     *@return array 会员ID数组
     */
    public function distributors(){
        $str="select m.id from pft_member_relationship r join pft_member m on r.son_id=m.id where r.status=0 and m.status=0 and r.ship_type=0 and parent_id=".$this->memberID;
        $GLOBALS['le']->query($str);
        $r=array();
        while($row=$GLOBALS['le']->fetch_assoc()){
            $r[]=$row['id'];
        }
        return $r;
    }

    /**
     *查询会员合作供应商函数.
     *@return array 会员ID数组
     */
    public function appiers(){
        $str="select m.id from pft_member_relationship r join pft_member m on r.parent_id=m.id where r.status=0 and m.status=0 and r.ship_type=0 and son_id=".$this->memberID;
        $GLOBALS['le']->query($str);
        $r=array();
        while($row=$GLOBALS['le']->fetch_assoc()){
            $r[]=$row['id'];
        }
        return $r;
    }
    
    /**
     *查询已配置账单设置分销商.
     *@return array 会员ID数组
     */
    public function settlefids(){
        $str="select fid from uu_settle where aid=".$this->memberID;
        $GLOBALS['le']->query($str);
        $r=array();
        while($row=$GLOBALS['le']->fetch_assoc()){
            $r[]=$row['fid'];
        }
        return $r;
    }
    
    /**
     *查询已配置账单设置供应商.
     *@return array 会员ID数组
     */
    public function settleaids(){
        $str="select aid from uu_settle where fid=".$this->memberID;
        $GLOBALS['le']->query($str);
        $r=array();
        while($row=$GLOBALS['le']->fetch_assoc()){
            $r[]=$row['aid'];
        }
        return $r;
    }
    
    /**
     *查询会员供应产品数.
     *@return int 
     */
    public function supplierNum(){
        $str="select count(*) as num from pft_member_relationship where status=0 and ship_type=0 and son_id=".$this->memberID;
        $GLOBALS['le']->query($str);
        $GLOBALS['le']->fetch_assoc();
        return $GLOBALS['le']->f("num");
    }


    public function getTotal($where)
    {
        $get_total    = "SELECT COUNT(DISTINCT lid) from pft_p_apply_evolute WHERE $where";
        $stmt       = Db::Connect()->prepare($get_total);
        $stmt->execute();
        $total      = $stmt->fetchColumn(0);
        return $total;
    }

    /**
     *查询会员可分销产品信息.
     *@param $lid 景区id，默认不传，传入只返回改景区产品
     *@return array 会员可分销产品，含直接供应和转供应产品
     */
    public function salePros($lid=Null){
        $where = " fid=? AND status=0";
//        $total =  $this->getTotal($where);
        $offset = 0;
        $size = 10;

        $get_lid_sql    = "SELECT DISTINCT lid from pft_p_apply_evolute WHERE $where LIMIT $offset,$size";
        $stmt           = Db::Connect()->prepare($get_lid_sql);
        $stmt->execute();
        $lid_str = implode(',', $stmt->fetchAll(\PDO::FETCH_COLUMN));

        //获取可销售产品ID
        $sql_sale_pid = <<<SQL
        SELECT pid,sid,lid FROM pft_p_apply_evolute WHERE fid=? AND lid IN($lid_str)
SQL;
        $pid_list = $data = array();
        $stmt = Db::Connect()->prepare($sql_sale_pid);
        $stmt->execute(array());
        while($row=$stmt->fetch(\PDO::FETCH_ASSOC)) {
            $pid_list[] = $row['pid'];
            $data[]     = $row;
        }

        $output = array();
        array_walk($ab, function($val, $key) use(&$output){
            if ($val>1) $output[] = $key;
        }) ;


        $pid_str = implode(',', array_unique($pid_list));

        //获取产品信息
        $sql_tpl = <<<SQL
SELECT p.id as pid,p.contact_id,p.apply_did,p.p_status,t.id as tid,t.pay,
t.getaddr,t.title,t.tprice,t.notes,t.buy_limit_low,t.status,t.order_end,
t.order_start,t.delaytype FROM uu_products p
LEFT JOIN uu_jq_ticket t ON p.id=t.pid
WHERE p.id IN($pid_str) p.p_status=0 AND p.apply_limit=1
SQL;

        $stmt = Db::Connect()->prepare($sql_tpl);
        $stmt->execute();
        $sale_list = array();
        while($row=$stmt->fetch(\PDO::FETCH_ASSOC)) {
            $sale_list[$row['id']] = $row;
        }
        $output = array();
        foreach ($data as $r) {
            $output[$r['lid']][] = array_merge($r, $sale_list[$r['pid']]);
        }
        return $output;
    }

    public function data_move($fid=94)
    {
        $sql = "select pids,aid from pft_product_sale_list where fid=$fid AND pids<>''";
        $stmt = Db::Connect()->prepare($sql);
        $stmt->execute();
        $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $total = 0;
        $str_val  = '';
        foreach ($data as $row) {
            if ($row['pids']=='A') {
                $all_list[] = $row['aid'];
            } else {
                $pid_arr[$row['aid']] = explode(',', $row['pids']);
            }
        }

        $str = 'INSERT INTO pft_p_apply_evolute(fid,sid,sourceid,pid,lvl,aids) VALUES';
        //等于A的产品处理
        if (count($all_list)) {
            $apply_did = implode(',', $all_list);
            $sql_all = "SELECT id,apply_did FROM uu_products WHERE apply_did IN(".$apply_did.")";
            $stmt = Db::Connect()->prepare($sql_all);
            $stmt->execute();
            while($row=$stmt->fetch(\PDO::FETCH_ASSOC)) {
                $str_val .= ",($fid,{$row['apply_did']},{$row['apply_did']},{$row['id']},1,{$row['apply_did']})";
            }
        }
        if (count($pid_arr)) {
            foreach($pid_arr as $aid=>$pid_list) {
                foreach ($pid_list as $pid) {
                    $str_val .= ",($fid,$aid,$aid,$pid,0,$aid)";
                    $total += 1;
                }
            }
        }

        $str_val = rtrim(',', $str_val);

        echo $str . $str_val;
        exit;
        $sql_2 = "SELECT pid,sid FROM pft_p_apply_evolute WHERE fid=4";
        $stmt = Db::Connect()->prepare($sql_2);
        $stmt->execute();
        $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
        foreach ($data as $row) {
            $total += 1;
            $pid_arr[$row['sid']] = $row['pid'];
        }
    }
}

/**
 *普通会员类.
 *可分销产品以传入分销商ID为准，分销价按零售价计算
 */
class GuestMember extends Member{
    public function __construct($s,$memberID,$fid){
        parent::__construct($s,$memberID);
        $this->fid=$fid;
    }
}
?>